import java.security.MessageDigest

class MD5Codec {
	// Returns the byte[] of the digest
    static encodeMethod = { theTarget ->
		if (theTarget == null) {
			return null
		} else {
			def md = MessageDigest.getInstance("MD5")
			md.update(theTarget.toString().getBytes()) // This probably needs to use the thread's Locale encoding
			return md.digest()
		}
	}

	static decode = { theTarget ->
		throw new UnsupportedOperationException("Cannot decode MD5 hashes")
	}

    static encode = { text ->

        def str = MD5Codec.encodeMethod(text)

        def hexOutput = new char[str.length * 2]

        def hexString


        for (int i = 0; i < str.length; i++) {

            hexString = "00" + Integer.toHexString(str[i])

            hexString.toLowerCase().getChars(hexString.length() - 2, hexString.length(), hexOutput, i * 2)

        }

        return new String(hexOutput)
    }
}